package com.tarena.lbs.basic.web.dao.repository.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tarena.lbs.base.protocol.pager.BasePageList;
import com.tarena.lbs.basic.web.dao.mapper.BusinessMapper;
import com.tarena.lbs.basic.web.dao.repository.BusinessRepository;
import com.tarena.lbs.pojo.basic.bo.BusinessBO;
import com.tarena.lbs.pojo.basic.dos.BusinessDO;
import com.tarena.lbs.pojo.basic.query.BusinessQuery;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Repository
public class BusinessRepositoryImpl implements BusinessRepository {
    @Autowired
    private BusinessMapper businessMapper;
    @Override
    public BasePageList<BusinessBO> getBusinessListByQuery(BusinessQuery businessQuery) {
        //1.开启PageHelper查询
        PageHelper.startPage(businessQuery.getPageNo(), businessQuery.getPageSize());
        List<BusinessDO> dos= businessMapper.selectBusinessByQuery(businessQuery);

        //2.使用pageHelper拿到total
        PageInfo<BusinessDO> pageDOS = new PageInfo<>(dos);
        //3.封装一个BasePageList
        List<BusinessBO> bos = new ArrayList<>();
        if (pageDOS.getTotal()!=0){
            pageDOS.getList().stream().forEach(bDo -> {
                BusinessBO bo = new BusinessBO();
                BeanUtils.copyProperties(bDo,bo);
                bos.add(bo);
            });
        }

        return new BasePageList<>(bos,pageDOS.getTotal());
    }

    @Override
    public Integer save(BusinessBO businessBO) {
        log.debug("保存商家数据BusinessBO:{}",businessBO);
        //BO转化为DO
        BusinessDO businessDO = new BusinessDO();
        if (businessBO!=null){
            BeanUtils.copyProperties(businessBO,businessDO);
        }
        //2.新增
        businessMapper.insert(businessDO);
        return businessDO.getId();
    }

    @Override
    public Long countBusinessById(Integer businessId) {
        return businessMapper.selectCountById(businessId);
    }
}
